package com.dongdongshop.service.impl;

import com.dongdongshop.config.ItemPageConfigurer;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemPageServiceImpl implements ItemPageService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @DubboReference
    private GoodsService gs;

    @DubboReference
    private GoodsDescService gds;

    @DubboReference
    private ItemService is;

    @Override
    public void createPage(Long goodsId) {
        //创建配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //获取模板对象
        Template template = null;
        FileWriter writer = null;
        try {
            template = configuration.getTemplate("item.ftl");

            TbGoods goods = gs.getGoodsById(goodsId);
            TbGoodsDesc goodsDesc = gds.getGoodsDescById(goodsId);
            List<TbItem> itemList = is.selectItemListByGoodsId(goodsId);
            //创建模板对象所需要的数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("goods",goods);
            map.put("goodsDesc",goodsDesc);
            map.put("itemList",itemList);

            //创建输出对象,并指定输出位置
            writer = new FileWriter("E:\\freemarker\\" + goodsId + ".html");
            //调用模板对象输出
            template.process(map, writer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            //关流
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
